package com.zsh.wanandroid.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.zsh.wanandroid.R;
import com.zsh.wanandroid.api.Api;
import com.zsh.wanandroid.api.ApiService;
import com.zsh.wanandroid.base.BaseActivity;
import com.zsh.wanandroid.bean.ScoreUserResult;
import com.zsh.wanandroid.common.APP;
import com.zsh.wanandroid.common.AppManager;
import com.zsh.wanandroid.http.ApiRequest;
import com.zsh.wanandroid.http.SaveCookiesInterceptor;
import com.zsh.wanandroid.impl.DialogClickListener;
import com.zsh.wanandroid.utils.UIUtils;

import java.util.logging.LogRecord;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * @author zsh
 * @date 2020/3/12.
 * 功能：我的页面
 */

public class MineActivity extends BaseActivity {

    private ImageView ivBack;
    private TextView tvTitle;
    private ImageView ivMore;
    private TextView tvLogin;
    private TextView tvLevel;
    private TextView tvRank;
    private TextView tvScore;

    private LinearLayout llScore;//积分
    private LinearLayout llLike;//收藏
    private LinearLayout llShare;//分享
    private LinearLayout llTodo;//TODO
    private LinearLayout llSetting;//设置
    private LinearLayout llLogout;//退出

    private String userScore = "";

    @Override
    public void initPrams(Bundle prams) {

    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_mine;
    }

    @Override
    public void initView(View view) {
        ivBack = $(R.id.ivBack);
        tvTitle = $(R.id.tvTitle);
        ivMore = $(R.id.ivMore);
        tvLogin = $(R.id.tvLogin);
        tvLevel = $(R.id.tvLevel);
        tvRank = $(R.id.tvRank);
        tvScore = $(R.id.tvScore);
        llScore = $(R.id.llScore);//积分
        llLike = $(R.id.llLike);//收藏
        llShare = $(R.id.llShare);//分享
        llTodo = $(R.id.llTodo);//TODO
        llSetting = $(R.id.llSetting);//设置
        llLogout = $(R.id.llLogout);//退出
    }

    @Override
    public void setListener() {
        ivBack.setOnClickListener(this);
        ivMore.setOnClickListener(this);
        tvLogin.setOnClickListener(this);
        llScore.setOnClickListener(this);
        llLike.setOnClickListener(this);
        llShare.setOnClickListener(this);
        llTodo.setOnClickListener(this);
        llSetting.setOnClickListener(this);
        llLogout.setOnClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack://返回
                back();
                break;

            case R.id.ivMore://积分榜
                startActivity(RankActivity.class);
                break;

            case R.id.tvLogin://去登陆
                if (!isLogin)
                    startActivityForResult(LoginActivity.class, 1);
                break;

            case R.id.llScore://积分
                //判断当前是否登录
                if (isLogin) {
                    Bundle bundle = new Bundle();
                    bundle.putString("scoreUser", userScore);
                    startActivity(ScoreActivity.class, bundle);
                } else {
                    startActivityForResult(LoginActivity.class, 1);
                }
                break;

            case R.id.llTodo://todo
                startActivity(TodoActivity.class);
                break;

            case R.id.llLogout://退出登录、
                UIUtils.normalDialog(self, R.style.BDAlertDialog, "确认退出登录？", "取消", "确认", new DialogClickListener() {
                    @Override
                    public void onNegativeClick() {
                        //取消
                    }

                    @Override
                    public void onPositiveClick() {
                        //确认
                        logout();
                    }
                });
                break;
        }
    }

    @Override
    public void doBusiness(Bundle savedInstanceState) {
        //设置标题
        tvTitle.setText("我的");
        ivMore.setImageResource(R.drawable.ic_rank_white_24dp);
        //获取个人信息
        getUserInfo();
    }

    private void back() {
        this.finish();
    }

    /**
     * 获取个人积分
     */
    private void getUserInfo() {
        ApiService apiService = ApiRequest.getInstance(self).create(ApiService.class);
        apiService.getUserInfo().enqueue(new Callback<ScoreUserResult>() {
            @Override
            public void onResponse(Call<ScoreUserResult> call, Response<ScoreUserResult> response) {
                ScoreUserResult body = response.body();
                if (body.getErrorCode() == Api.ERRORCODE) {
                    showInfo();
                } else {
                    showUserInfo(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<ScoreUserResult> call, Throwable t) {
                UIUtils.showToast("请求数据失败");
            }
        });
    }

    private void showUserInfo(ScoreUserResult.Data data) {
        tvLogin.setText(data.getUsername());
        tvLevel.setText("等级："+data.getLevel());
        tvRank.setText("排名："+data.getRank());
        userScore = data.getCoinCount()+"";
        tvScore.setText(userScore);
        llLogout.setVisibility(View.VISIBLE);
    }

    private void showInfo() {
        tvLogin.setText("去登陆");
        tvLevel.setText("等级：--");
        tvRank.setText("排名：--");
        userScore = "";
        tvScore.setText(userScore);
        llLogout.setVisibility(View.GONE);
    }

    /**
     * 退出登录
     */
    private void logout() {
        ApiService apiService = ApiRequest.getInstance(self).create(ApiService.class);
        apiService.logout().enqueue(new Callback<LogRecord>() {
            @Override
            public void onResponse(Call<LogRecord> call, Response<LogRecord> response) {
                //清除cookie
                SaveCookiesInterceptor.clearCookie(self);
                //清除登录状态
                SPUtils.getInstance(APP.currentAppName).put(APP.isLogin, false);
                showInfo();
            }

            @Override
            public void onFailure(Call<LogRecord> call, Throwable t) {
                showToast("网络错误");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            if (data.getExtras().getInt("result") == 0) {
                UIUtils.showToast("登录成功");
                getUserInfo();
            } else if (data.getExtras().getInt("result") == -1){
                UIUtils.showToast("登录失败");
            }
        }
    }
}
